//
//  PkViewController.m
//  CardWarrior
//
//  Created by Tekka Xie on 12-4-26.
//  Copyright (c) 2012年 Tencent. All rights reserved.
//

#import "PkViewController.h"
#import "AudioManager.h"
#import "AnimationHelper.h"
#import "FontManager.h"
#import "EasyGlyph.h"
#import "GameDataManager.h"
#import "PkManager.h"
#import "CardImageManager.h"
#import "AudioManager.h"

#define LEFT_DRAW_CARD_DST_X    120
#define LEFT_DRAW_CARD_DST_Y    75

#define RIGHT_DRAW_CARD_DST_X   299
#define RIGHT_DRAW_CARD_DST_Y   75

static float hostHandCardPosX[4] = { 75.0 , 115.0 , 155.0 , 195.0 };
static float hostHandCardPosY[4] = { 265.0 , 258.0 , 258.0 , 265.0 };
static float hostHandCardRot[4] = { -0.08333 , -0.02778 , 0.02778 , 0.08333 };
static float guestHandCardPosX[4] = { 284.0 , 324.0 , 364.0 , 404.0 };
static float guestHandCardPosY[4] = { 265.0 , 258.0 , 258.0 , 265.0 };
static float guestHandCardRot[4] = { -0.08333 , -0.02778 , 0.02778 , 0.08333 };

@implementation PkViewController

#pragma mark - synthesize

@synthesize background02;
@synthesize hostRoleView;
@synthesize guestRoleView;
@synthesize blackRoundView;
@synthesize whiteRoundView;
@synthesize bannerView;
@synthesize hostScoreView;
@synthesize guestScoreView;
@synthesize hostNameView;
@synthesize guestNameView;
@synthesize hostCardStack;
@synthesize guestCardStack;
@synthesize hostDrawCard01;
@synthesize guestDrawCard01;
@synthesize hostTargetCard;
@synthesize guestTargetCard;
@synthesize hostTargetCardEffect;
@synthesize guestTargetCardEffect;
@synthesize hostAcceptView;
@synthesize guestAcceptView;
@synthesize pauseBtn;
@synthesize maskView;
@synthesize backBtn;
@synthesize playAgainBtn;
@synthesize backToMenuBtn;
@synthesize selectCharacterBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

enum ANIMATION_ID{
    WHITE_ROUND_ANIMATION_ID,
    BLACK_ROUND_ANIMATION_ID,
    MAX_ANIMATION_ID
};

void (^global_drawTargetCardAnimation)(BOOL finished);

void (^global_drawTargetCardAnimation_Step1)();
void (^global_drawTargetCardAnimation_Step1_Host)();
void (^global_drawTargetCardAnimation_Step1_Guest)();

void (^global_drawTargetCardAnimation_Step2)();
void (^global_drawTargetCardAnimation_Step2_Host)(NSTimeInterval duration, NSTimeInterval delay, BOOL checkValid);
void (^global_drawTargetCardAnimation_Step2_Guest)(NSTimeInterval duration, NSTimeInterval delay, BOOL checkValid);

void (^global_drawHostHandCard)(NSInteger index, NSTimeInterval delay);
void (^global_drawGuestHandCard)(NSInteger index, NSTimeInterval delay);

void (^global_acceptViewAnimation)();

void (^global_guestHandCardToTarget)(NSInteger index, BOOL isToHost);


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initReset];    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight
        || interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        return YES;
    
    return NO;
}

#pragma mark - init

- (void)initReset
{
    [[AudioManager sharedInstance] PlayBGM:@"FightingStartBGM"];
    [[GameDataManager sharedInstance] resetScore];
    
    @autoreleasepool {
    [self initAllViews];
    [self initGlobalBlock];
    
    if ([[GameDataManager sharedInstance] gameCurrentMode] == 1)
    {
        [NSTimer scheduledTimerWithTimeInterval:5
                                         target:self
                                       selector:@selector(timerStartAI:)
                                       userInfo:nil
                                        repeats:NO]; 
        
        for (NSInteger i = 0; i < 4; i++)
        {
            hostHandCard[i].userInteractionEnabled  = YES;
            guestHandCard[i].userInteractionEnabled = NO;
        }
    }
    else
    {
        for (NSInteger i = 0; i < 4; i++)
        {
            hostHandCard[i].userInteractionEnabled  = YES;
            guestHandCard[i].userInteractionEnabled = YES;
        }
    }
    
    [NSTimer scheduledTimerWithTimeInterval:4.1
                                     target:self
                                   selector:@selector(timerStartDrawHandBack:)
                                   userInfo:nil
                                    repeats:1]; 
    
    // 2. round,role,cardStack,text 动画
    void (^secondAnimation)(BOOL finished);
    secondAnimation = ^(BOOL finished)
    {    
        blackRoundView.alpha = 1.0;
        whiteRoundView.alpha = 1.0;
        hostRoleView.alpha = 1.0;
        guestRoleView.alpha = 1.0;
        hostCardStack.alpha = 1.0;
        guestCardStack.alpha = 1.0;
        hostScoreView.alpha = 0.0;
        guestScoreView.alpha = 0.0;
        hostNameView.alpha = 0.0;
        guestNameView.alpha = 0.0;
        
        float animationTime = 1.7;
        
        [AnimationHelper simpleAnimationForView:blackRoundView
                                    withOptions:ANIMATION_SCALE_MASK|ANIMATION_ROTATE_MASK_COUNTER
                                       duration:animationTime];
        [AnimationHelper simpleAnimationForView:whiteRoundView
                                    withOptions:ANIMATION_SCALE_MASK|ANIMATION_ROTATE_MASK_CLOCK
                                       duration:animationTime];
        [AnimationHelper simpleAnimationForView:hostRoleView
                                    withOptions:ANIMATION_SCALE_MASK
                                       duration:animationTime];
        [AnimationHelper simpleAnimationForView:guestRoleView
                                    withOptions:ANIMATION_SCALE_MASK
                                       duration:animationTime];
        [AnimationHelper simpleAnimationForView:hostCardStack
                                    withOptions:ANIMATION_SCALE_MASK
                                       duration:animationTime];
        [AnimationHelper simpleAnimationForView:guestCardStack
                                    withOptions:ANIMATION_SCALE_MASK
                                       duration:animationTime];
        
        [UIView animateWithDuration: animationTime  delay: 0.0
                            options: UIViewAnimationOptionShowHideTransitionViews
                         animations: ^(){
                             hostScoreView.alpha = 1.0;
                             guestScoreView.alpha = 1.0;
                             hostNameView.alpha = 1.0;
                             guestNameView.alpha = 1.0;
                         }
                         completion: global_drawTargetCardAnimation
         ];
        
    };
    
    // 1. 背景动画展示
    [UIView animateWithDuration: 0.5  delay: 0.5
                        options: UIViewAnimationOptionShowHideTransitionViews
                     animations: ^(){
                         background02.alpha = 1.0;
                         bannerView.alpha = 1.0;
                     }
                     completion: secondAnimation
     ];
    }
}

- (void)initAllViews
{
    background02.alpha = 0;
    hostRoleView.alpha = 0;
    guestRoleView.alpha = 0;
    blackRoundView.alpha = 0;
    whiteRoundView.alpha = 0;
    bannerView.alpha = 0;
    hostCardStack.alpha = 0;
    guestCardStack.alpha = 0;
    hostScoreView.alpha = 0;
    guestScoreView.alpha = 0;
    hostNameView.alpha = 0;
    guestNameView.alpha = 0;
    hostDrawCard01.alpha = 0;
    guestDrawCard01.alpha = 0;
    hostTargetCard.alpha = 0;
    guestTargetCard.alpha = 0;
    hostTargetCardEffect.alpha = 0;
    guestTargetCardEffect.alpha = 0;
    hostAcceptView.alpha = 0;
    guestAcceptView.alpha = 0;
    maskView.alpha = 0;
    backBtn.alpha = 0;
    playAgainBtn.alpha = 0;
    backToMenuBtn.alpha = 0;
    selectCharacterBtn.alpha = 0;
    
    endBGMHasBegan = NO;
    
    for (int i = 0; i < 4; i++)
    {
        hostCardEffect[i] = (UIImageView*)[[self view] viewWithTag:i+100];
        guestCardEffect[i] = (UIImageView*)[[self view] viewWithTag:i+200];
        hostHandCard[i] = (UIImageView*)[[self view] viewWithTag:i+300];
        guestHandCard[i] = (UIImageView*)[[self view] viewWithTag:i+400];
        hostHandCardValid[i] = YES;
        guestHandCardValid[i] = YES;
    }
    
    for (int i = 0; i < 4; i++)
    {
        hostCardEffect[i].alpha = 0.0;
        guestCardEffect[i].alpha = 0.0;
        hostHandCard[i].alpha = 0.0;
        guestHandCard[i].alpha = 0.0;
    }
    
    currentCardValid = YES;
    [self setRoleView];
    [self setScoreView];
    [self setNameView];
    [self setHandCardView];
}

- (void)setRoleView
{
    @autoreleasepool {
    GameDataManager* pManager = [GameDataManager sharedInstance];
    
    NSInteger hostIndex = pManager.hostSelectedRole;
    NSInteger guestIndex = pManager.guestSelectedRole;
    
    __autoreleasing NSDictionary* pHostDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:hostIndex]];
    __autoreleasing NSDictionary* pGuestDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:guestIndex]];
    
    if (pManager.hostScore > pManager.guestScore)
        hostRoleView.image = [UIImage imageNamed:[pHostDictionary objectForKey:@"lose_pic"]];
    else
        hostRoleView.image = [UIImage imageNamed:[pHostDictionary objectForKey:@"win_pic"]];
    
    if (pManager.hostScore < pManager.guestScore)
        guestRoleView.image = [UIImage imageNamed:[pGuestDictionary objectForKey:@"lose_pic"]];
    else
        guestRoleView.image = [UIImage imageNamed:[pGuestDictionary objectForKey:@"win_pic"]];
    }
}

- (void)setScoreView
{    
    GameDataManager* pData = [GameDataManager sharedInstance];
 
    @autoreleasepool 
    {
        __autoreleasing NSString* text = [NSString stringWithFormat:@"%d", pData.hostScore];
        [[FontManager sharedInstance] setFontForView:hostScoreView WithSize:25 WithString:text];

        text = [NSString stringWithFormat:@"%d", pData.guestScore];
        [[FontManager sharedInstance] setFontForView:guestScoreView WithSize:25 WithString:text];
    }
    
    // 根据比分决定是否gameover
    if (pData.hostScore == 0 || pData.guestScore == 0)
    {        
        if (pData.gameCurrentMode == 1)
        {
            if (pData.hostScore == 0)
            {
                pData.whoWin = 1;
                pData.hostWinCount += pData.difficulty;
            }
            else
            {
                pData.whoWin = 2;
            }
        }
        else if (pData.gameCurrentMode == 2)
        {
            if (pData.hostScore == 0)
            {
                pData.whoWin = 1;
                pData.hostWinCount += pData.difficulty;
            }
            else 
            {
                pData.whoWin = 2;
                pData.guestWinCount += pData.difficulty;
            }
        }

        [NSTimer scheduledTimerWithTimeInterval:1.5
                                         target:self
                                       selector:@selector(timerTransToResultView:)
                                       userInfo:nil
                                        repeats:NO];
    }
}

- (void)setNameView
{
    @autoreleasepool {
    GameDataManager* pManager = [GameDataManager sharedInstance];
    
    // hostName
    __autoreleasing NSDictionary* pDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:pManager.hostSelectedRole]];

    __autoreleasing NSString* textName = [pDictionary objectForKey:@"name"];
    [[FontManager sharedInstance] setFontForView:hostNameView WithSize:12 WithString:textName];
    
    // guestName
    pDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:pManager.guestSelectedRole]];
    textName = [pDictionary objectForKey:@"name"];
    [[FontManager sharedInstance] setFontForView:guestNameView WithSize:12 WithString:textName];
    }
}

- (void)drawTargetCard
{
    @autoreleasepool {
    [self drawAndGetImage:hostTargetCardEffect drawHost:YES];
    [self drawAndGetImage:guestTargetCardEffect drawHost:NO];
    }
}

- (void)setHandCardView
{
    @autoreleasepool {
    for (NSInteger i = 0; i < 4; i++)
    {
        [self drawAndGetImage:hostHandCard[i] drawHost:YES];
        [self drawAndGetImage:guestHandCard[i] drawHost:NO];
    }
    }
}

- (void)showHiddenMenu
{
    [UIView animateWithDuration: 0.4  delay: 0
                        options: UIViewAnimationOptionCurveEaseIn
                     animations: ^(){
                         maskView.alpha = 1.0;
                         backBtn.alpha =1.0;
                         playAgainBtn.alpha = 1.0;
                         backToMenuBtn.alpha = 1.0;
                         selectCharacterBtn.alpha = 1.0;
                     }
                     completion: nil
     ];
}

- (void)hideMenu
{
    [UIView animateWithDuration: 0.4  delay: 0
                        options: UIViewAnimationOptionCurveEaseIn
                     animations: ^(){
                         maskView.alpha = 0;
                         backBtn.alpha = 0;
                         playAgainBtn.alpha = 0;
                         backToMenuBtn.alpha = 0;
                         selectCharacterBtn.alpha = 0;
                     }
                     completion: nil
     ];
}

- (void)drawAndGetImage:(UIImageView*)view drawHost:(BOOL)isDrawHost
{
    @autoreleasepool {
    GameDataManager* pData = [GameDataManager sharedInstance];
    if (view.tag >= 400 && view.tag < 500 && [pData guestScore] < 5)
    {
        guestHandCardValid[view.tag - 400] = NO;
        return ;
    }
    else if (view.tag >=300 && (view.tag < 400) && [pData hostScore] < 5)
    {
        hostHandCardValid[view.tag - 300] = NO;
        return ;
    }
    
    NSInteger drawnCard = [[PkManager sharedInstance] drawCard:isDrawHost];
    view.image = [[CardImageManager sharedInstance] GetImage:drawnCard];
    
    drawnCard++;
    while (drawnCard > 13) drawnCard -= 13;
    
    NSNumber* thirteenNumber = [NSNumber numberWithInt: drawnCard];
    
    [view.layer setValue:thirteenNumber forKey:@"CardNumber"];
    
    [self switchCardStackStatus];  
    }
}

- (void)switchCardStackStatus
{
    @autoreleasepool {
    PkManager* pk = [PkManager sharedInstance];
    
    if (pk.hostCardCount == 15)
        hostCardStack.image = [UIImage imageNamed:@"PkCardStack02.png"];
    else if (pk.hostCardCount == 10)
        hostCardStack.image = [UIImage imageNamed:@"PkCardStack03.png"];
    else if (pk.hostCardCount == 5)
        hostCardStack.image = [UIImage imageNamed:@"PkCardStack04.png"];
    else if (pk.hostCardCount == 0)
        hostCardStack.alpha = 0.0;
    
    if (pk.guestCardCount == 15)
        guestCardStack.image = [UIImage imageNamed:@"PkCardStack02.png"];
    else if (pk.guestCardCount == 10)
        guestCardStack.image = [UIImage imageNamed:@"PkCardStack03.png"];
    else if (pk.guestCardCount == 5)
        guestCardStack.image = [UIImage imageNamed:@"PkCardStack04.png"];
    else if (pk.guestCardCount == 0)
        guestCardStack.alpha = 0.0;
    }
}

- (void)clearAllData
{
    @autoreleasepool {
    [[GameDataManager sharedInstance] clearPkData];
    [[PkManager sharedInstance] clearPkData];
    }
}

#pragma mark - times

- (void)timerStartDrawHandBack:(NSTimer*)theTimer
{
    @autoreleasepool {
    [theTimer invalidate];
    
    [[AudioManager sharedInstance] PlaySFX:@"SlideSFX"];
    
    [NSTimer scheduledTimerWithTimeInterval:0.1
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:nil
                                    repeats:YES];
    }
}
         
- (void)timerFireMethod:(NSTimer*)theTimer
{
    @autoreleasepool {
    static int i = 0;

    global_drawHostHandCard(i, 0);
    global_drawGuestHandCard(i, 0);
    
    if (i == 3)
    {
        [theTimer invalidate];
        i = 0;
    }
    else i++;
    }
}

// 检测当前TargetCard和HandCard是否有有效组合，无效的话重新抽2边的TargetCard
- (void)checkCurrentIsValid
{   
    @autoreleasepool {
    NSTimeInterval delay;
    if (currentCardValid == NO)
        delay = 0;
    else 
        delay = 0.5;
    [NSTimer scheduledTimerWithTimeInterval:delay
                                     target:self
                                   selector:@selector(timerCheckCurrentIsValid:)
                                   userInfo:nil
                                    repeats:NO];
    }
}

- (void)timerCheckCurrentIsValid:(NSTimer*)timer
{
    @autoreleasepool {
    PkManager* pkManager =  [PkManager sharedInstance];
    for (NSInteger i = 0; i < 4; i++)
    {
        if (hostHandCardValid[i] && [pkManager checkCardWhetherMarch:hostTargetCard withView:hostHandCard[i]])
        {
            currentCardValid = YES;
            return ;
        }
        if (hostHandCardValid[i] && [pkManager checkCardWhetherMarch:guestTargetCard withView:hostHandCard[i]])
        {
            currentCardValid = YES;
            return ;
        }
        if (guestHandCardValid[i] && [pkManager checkCardWhetherMarch:hostTargetCard withView:guestHandCard[i]])
        {
            currentCardValid = YES;
            return ;
        }
        if (guestHandCardValid[i] && [pkManager checkCardWhetherMarch:guestTargetCard withView:guestHandCard[i]])
        {
            currentCardValid = YES;
            return ;
        }
    }
    
    if ([[GameDataManager sharedInstance] hostScore] == 0 ||
        [[GameDataManager sharedInstance] guestScore] == 0)
        return ;
    
    if (currentCardValid == NO)
        return ;
    
    currentCardValid = NO;
    
    if (pkManager.hostCardCount == 0 || pkManager.guestCardCount == 0)
    {
        // 任意匹配
        global_acceptViewAnimation();
    }
    else
    {
        // 抽TargetCard
        
        // 双方Score减1
        [[GameDataManager sharedInstance] minusHostScore];
        [[GameDataManager sharedInstance] minusGuestScore];
        
        // 重新抽TargetCard动画
        global_drawTargetCardAnimation(NO);
    }
    }
    
    return ;
}

- (void)timerTransToResultView:(NSTimer*)timer
{
    @autoreleasepool {
    [self clearAllData];
    [self performSegueWithIdentifier:@"SegueToResultViewController" sender:nil];
    }
}

- (void)timerPlayAgain:(NSTimer*)timer
{
    @autoreleasepool {
    [self hideMenu];
    [self initReset];
    }
}

- (void)timerStartAI:(NSTimer*)timer
{
    @autoreleasepool {
    GameDataManager* pData = [GameDataManager sharedInstance];
    
    NSTimeInterval interval;
    if (pData.difficulty == 3)
        interval = 1.5;
    else 
        interval = 2.0;
    
    [NSTimer scheduledTimerWithTimeInterval:interval
                                     target:self
                                   selector:@selector(timerAIProcess:)
                                   userInfo:nil
                                    repeats:YES]; 
    }
}

- (void)timerAIProcess:(NSTimer*)timer
{
    @autoreleasepool {
    
    PkManager* pkManager =  [PkManager sharedInstance];
    
    for (NSInteger i = 0; i < 4; i++)
    {

        if (guestHandCardValid[i] && [pkManager checkCardWhetherMarch:hostTargetCard withView:guestHandCard[i]])
        {
            global_guestHandCardToTarget(i, YES);
            return ;
        }
        
        if (guestHandCardValid[i] && [pkManager checkCardWhetherMarch:guestTargetCard withView:guestHandCard[i]])
        {
            global_guestHandCardToTarget(i, NO);
            return ;
        }
        
        if (guestHandCardValid[i] && currentCardValid == NO && (pkManager.hostCardCount == 0 ||pkManager.guestCardCount == 0))
        {
            global_guestHandCardToTarget(i, NO);
            return ;
        }
    }
    }
}


#pragma mark - animation delegate

- (void)animationWillStart:(NSString *)animationID context:(void *)context
{
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    if (animationID == @"SECOND_ANIMATION")
    {
        
    }
}

#pragma mark - touches

static UIImageView* selectedCardView = nil;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    @autoreleasepool {
    
    UITouch *touch = [[event allTouches] anyObject];
    UIImageView *touchView = (UIImageView*)[touch view];
    
    NSNumber* pHost = [hostTargetCard.layer valueForKey:@"CardNumber"];
    NSNumber* pGuest = [guestTargetCard.layer valueForKey:@"CardNumber"];
    NSLog(@"hostTarget: %d, guestTarget: %d", [pHost integerValue], [pGuest integerValue]);
    
    if (touchView.tag >= 300 && touchView.tag < 500)
    {
        // click HandCard
        [[AudioManager sharedInstance] PlaySFX:@"CardoutSFX"];
        
        [UIView animateWithDuration: 0.1  delay: 0.0
                            options: UIViewAnimationCurveLinear
                         animations: ^(){
                             touchView.transform = CGAffineTransformIdentity;
                         }
                         completion: nil
         ];
        
        selectedCardView = touchView;
    }
    else if (touchView == pauseBtn)
    {
        [self showHiddenMenu];
    }
    else if (touchView == backBtn)
    {
        [self hideMenu];
    }
    else if (touchView ==  playAgainBtn || touchView == backToMenuBtn || touchView == selectCharacterBtn)
    {   
        if (touchView.highlighted == NO)
        {
            playAgainBtn.highlighted = NO;
            backToMenuBtn.highlighted = NO;
            selectCharacterBtn.highlighted = NO;
            
            touchView.highlighted = YES;
            [[AudioManager sharedInstance] PlaySFX:@"SelectSFX"];
        }
        else
        {
            [[AudioManager sharedInstance] PlaySFX:@"ConfirmSFX"];
            
            [self clearAllData];
            if (touchView == playAgainBtn)
            {
                [NSTimer scheduledTimerWithTimeInterval:0.7
                                                 target:self
                                               selector:@selector(timerPlayAgain:)
                                               userInfo:nil
                                                repeats:NO];
            }
            else if (touchView == backToMenuBtn)
            {
                [self hideMenu];
                [[AudioManager sharedInstance] PlayBGM:@"WelcomeBGM"];
                [self performSegueWithIdentifier:@"SegueToMainViewController" sender:nil];
            }
            else if (touchView == selectCharacterBtn)
            {
                [self hideMenu];
                [[AudioManager sharedInstance] PlayBGM:@"WelcomeBGM"];
                [self performSegueWithIdentifier:@"SegueToRoleSelectViewController" sender:nil];
            }
        }
    }
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    @autoreleasepool {    
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:[self view]];
    
    if (selectedCardView)
    {
        selectedCardView.center = location;
        PkManager* pk = [PkManager sharedInstance];
        
        // blackRoundView 状态控制
        if ([blackRoundView pointInside:[touch locationInView:blackRoundView]  withEvent:nil] ==  YES)
        {
            if ([pk checkCardWhetherMarch:hostTargetCardEffect withView:selectedCardView])
                blackRoundView.highlighted = YES;
            else if(currentCardValid == NO && (pk.hostCardCount == 0 ||pk.guestCardCount == 0))
                blackRoundView.highlighted = YES;
            else
                blackRoundView.highlighted = NO;
        }
        else 
            blackRoundView.highlighted = NO;
        
        // whiteRoundView 状态控制
        if ([whiteRoundView pointInside:[touch locationInView:whiteRoundView]   withEvent:nil] == YES)
        {
            if ([pk checkCardWhetherMarch:guestTargetCardEffect withView:selectedCardView])
                whiteRoundView.highlighted = YES;
            else if(currentCardValid == NO && (pk.hostCardCount == 0 ||pk.guestCardCount == 0))
                whiteRoundView.highlighted = YES;
            else 
                whiteRoundView.highlighted = NO;
        }
        else
            whiteRoundView.highlighted = NO;
    }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    @autoreleasepool {
    UITouch *touch = [[event allTouches] anyObject];
    UIImageView *touchView = (UIImageView*)[touch view];
    
    if (selectedCardView)
    {
        UIImageView* matchedViewEffect = nil;
        if (blackRoundView.highlighted == YES)
            matchedViewEffect = hostTargetCardEffect;
        else if (whiteRoundView.highlighted == YES)
            matchedViewEffect = guestTargetCardEffect;
        
        [[AudioManager sharedInstance] PlaySFX:@"CardbackSFX"];
        
        if (matchedViewEffect)
        {
            // 匹配
            matchedViewEffect.image = selectedCardView.image;
            [matchedViewEffect.layer setValue:[selectedCardView.layer valueForKey:@"CardNumber"] 
                                    forKey:@"CardNumber"];
            
            if (touchView.tag >= 400 && touchView.tag < 500)
                [self drawAndGetImage:selectedCardView drawHost:NO];
            else 
                [self drawAndGetImage:selectedCardView drawHost:YES];
            
            if (matchedViewEffect == hostTargetCardEffect)
                global_drawTargetCardAnimation_Step2_Host(0.3, 0, YES);
            else 
                global_drawTargetCardAnimation_Step2_Guest(0.3, 0, YES);
            
            if (selectedCardView.tag < 400)
            {
                [[GameDataManager sharedInstance] minusHostScore];
                global_drawHostHandCard(selectedCardView.tag-300, 0.2);
            }
            else
            {
                [[GameDataManager sharedInstance] minusGuestScore];
                global_drawGuestHandCard(selectedCardView.tag-400, 0.2);
            }
            
            // gameover,禁止对卡片操作
            if ([[GameDataManager sharedInstance] hostScore] == 0 ||
                [[GameDataManager sharedInstance] guestScore] == 0)
            {
                for (NSInteger i = 0; i < 4; i++)
                {
                    hostHandCard[i].userInteractionEnabled  = NO;
                    guestHandCard[i].userInteractionEnabled = NO;
                }
            }
            
            // 根据比较重置角色表情
            if ([[PkManager sharedInstance] hostCardCount] < 22)
                [self setRoleView];
            
            // 变更bgm为紧张节奏
            if ([[GameDataManager sharedInstance] hostScore] == 5 ||
                [[GameDataManager sharedInstance] guestScore] == 5)
            {
                if (endBGMHasBegan == NO)
                {
                    endBGMHasBegan = YES;
                    [[AudioManager sharedInstance] PlayBGM:@"FightingWillEndBGM"];
                }
            }
        }
        else
        {
            // 移动的HandCard回归原位
            NSInteger index;
            CGFloat rotation;
            CGPoint position;
            if (touchView.tag < 400)
            {
                index = touchView.tag-300;
                rotation = M_PI*hostHandCardRot[index];
                position = CGPointMake(hostHandCardPosX[index], hostHandCardPosY[index]);
            }
            else
            {
                index = touchView.tag-400;
                rotation = M_PI*guestHandCardRot[index];
                position = CGPointMake(guestHandCardPosX[index], guestHandCardPosY[index]);
            }
            
            [UIView animateWithDuration: 0.2  delay: 0.0
                                options: UIViewAnimationCurveLinear
                             animations: ^(){
                                 selectedCardView.center = position;
                                 selectedCardView.transform = CGAffineTransformMakeRotation(rotation);
                             }
                             completion: nil
             ];
        }
    }
    
    selectedCardView = nil;
    blackRoundView.highlighted = NO;
    whiteRoundView.highlighted = NO;
    }
}

#pragma mark - animation block

- (void)initGlobalBlock
{
    @autoreleasepool {
    
    global_drawTargetCardAnimation_Step1_Host = ^()
    {
        hostDrawCard01.alpha = 1.0;
        hostDrawCard01.frame = CGRectMake(173, 110, 54, 59);
        
        [UIView animateWithDuration: 0.4  delay: 0.0
                            options: UIViewAnimationOptionCurveEaseInOut
                         animations: ^(){
                             hostDrawCard01.frame = CGRectMake(LEFT_DRAW_CARD_DST_X, LEFT_DRAW_CARD_DST_Y, 54, 59);
                             hostDrawCard01.alpha = 0.0;
                         }
                         completion: nil
         ];
    };
    
    global_drawTargetCardAnimation_Step1_Guest = ^()
    {
        guestDrawCard01.alpha = 1.0;
        guestDrawCard01.frame = CGRectMake(246, 110, 54, 59);
        
        [UIView animateWithDuration: 0.4  delay: 0.0
                            options: UIViewAnimationOptionCurveEaseInOut
                         animations: ^(){
                             guestDrawCard01.frame = CGRectMake(RIGHT_DRAW_CARD_DST_X, RIGHT_DRAW_CARD_DST_Y, 54, 59);
                             guestDrawCard01.alpha = 0.0;
                         }
                         completion: nil
        ];

    };
    
    global_drawTargetCardAnimation_Step1= ^()
    {
        // 抽双方TargetCard
        global_drawTargetCardAnimation_Step1_Host();
        global_drawTargetCardAnimation_Step1_Guest();
    };
    
    global_drawTargetCardAnimation_Step2_Host = ^(NSTimeInterval duration, NSTimeInterval delay, BOOL checkValid)
    {
        // display hostTartCard scle effect
        hostTargetCardEffect.alpha = 0.0;
        hostTargetCardEffect.transform = CGAffineTransformMakeScale(0.1, 0.1);
        
        [UIView animateWithDuration: duration  delay: delay
                            options: UIViewAnimationOptionCurveEaseInOut
                         animations: ^(){
                             hostTargetCardEffect.alpha = 1.0;
                             hostTargetCardEffect.transform = CGAffineTransformMakeScale(1.0, 1.0);
                         }
                         completion: ^(BOOL finished){
                             hostTargetCard.alpha = 1.0;    
                             hostTargetCard.image = hostTargetCardEffect.image;
                             [hostTargetCard.layer setValue:[hostTargetCardEffect.layer valueForKey:@"CardNumber"] 
                                                     forKey:@"CardNumber"];
                             hostTargetCardEffect.alpha = 0.0;
                             [self setScoreView];
                             if (checkValid)
                                 [self checkCurrentIsValid];
                             
                             blackRoundView.highlighted = NO;
                         } 
         ];
        
    };
    
    global_drawTargetCardAnimation_Step2_Guest = ^(NSTimeInterval duration, NSTimeInterval delay, BOOL checkValid)
    {
        // display guestTartCard scle effect
        guestTargetCardEffect.alpha = 0.0;
        guestTargetCardEffect.transform = CGAffineTransformMakeScale(0.1, 0.1);
        
        [UIView animateWithDuration: duration  delay: delay
                            options: UIViewAnimationOptionCurveEaseInOut
                         animations: ^(){                             
                             guestTargetCardEffect.alpha = 1.0;
                             guestTargetCardEffect.transform = CGAffineTransformMakeScale(1.0, 1.0);
                         }
                         completion: ^(BOOL finished){
                             guestTargetCard.alpha = 1.0;
                             guestTargetCard.image = guestTargetCardEffect.image;
                             [guestTargetCard.layer setValue:[guestTargetCardEffect.layer valueForKey:@"CardNumber"] 
                                                      forKey:@"CardNumber"];
                             guestTargetCardEffect.alpha = 0.0;
                             [self setScoreView];
                             if (checkValid)
                                 [self checkCurrentIsValid];
                             
                             whiteRoundView.highlighted = NO;
                         } 
         ];
        
    };
    
    global_drawTargetCardAnimation_Step2 = ^()
    {
        global_drawTargetCardAnimation_Step2_Host(0.6, 0.4, NO);
        global_drawTargetCardAnimation_Step2_Guest(0.6, 0.4, YES);
    };
    
    // drawTargetCard animation
    global_drawTargetCardAnimation = ^(BOOL finished)
    {   
        [self drawTargetCard];
        
        global_drawTargetCardAnimation_Step1();
        global_drawTargetCardAnimation_Step2();
    };
    
    
    // drawHandCard animation
    global_drawHostHandCard = ^(NSInteger i, NSTimeInterval delay)
    {
        if (hostHandCardValid[i] == NO)
        {
            hostHandCard[i].alpha = 0.0;
            return ;
        }
        
        hostCardEffect[i].alpha = 1.0;
        hostCardEffect[i].center = CGPointMake(203, 127);
        
        [UIView animateWithDuration: 0.4  delay: 0.0 + delay
                            options: UIViewAnimationCurveLinear
                         animations: ^(){
                             hostCardEffect[i].alpha = 0.0;
                             hostCardEffect[i].center = CGPointMake(107, 220);
                         }
                         completion: nil
         ];
        
        hostHandCard[i].alpha = 0.0;
        hostHandCard[i].center = CGPointMake( 107, 220);
        hostHandCard[i].transform = CGAffineTransformIdentity;
        
        [UIView animateWithDuration: 0.4  delay: 0.3 + delay
                            options: UIViewAnimationCurveLinear
                         animations: ^(){
                             hostHandCard[i].alpha = 1.0;
                             hostHandCard[i].center = CGPointMake(hostHandCardPosX[i], hostHandCardPosY[i]);                             
                             hostHandCard[i].transform = CGAffineTransformMakeRotation(M_PI*hostHandCardRot[i]);
                         }
                         completion: nil
         ];
    };
    
    global_drawGuestHandCard = ^(NSInteger i, NSTimeInterval delay)
    {
        if (guestHandCardValid[i] == NO)
        {
            guestHandCard[i].alpha = 0.0;
            return ;
        }
        
        guestCardEffect[i].alpha = 1.0;
        guestCardEffect[i].center = CGPointMake(270, 127);
        
        [UIView animateWithDuration: 0.4  delay: 0.0 + delay
                            options: UIViewAnimationCurveLinear
                         animations: ^(){
                             guestCardEffect[i].alpha = 0.0;
                             guestCardEffect[i].center = CGPointMake(370, 220);   
                         }
                         completion: nil
         ];
        
        guestHandCard[i].alpha = 0.0;
        guestHandCard[i].center = CGPointMake( 370, 220);
        guestHandCard[i].transform = CGAffineTransformIdentity;
        
        [UIView animateWithDuration: 0.4  delay: 0.3 + delay
                            options: UIViewAnimationCurveLinear
                         animations: ^(){
                             guestHandCard[i].alpha = 1.0;
                             guestHandCard[i].center = CGPointMake(guestHandCardPosX[i], guestHandCardPosY[i]);                                
                             guestHandCard[i].transform = CGAffineTransformMakeRotation(M_PI*guestHandCardRot[i]);
                         }
                         completion: nil
         ];
    };

    // 感叹号闪动
    global_acceptViewAnimation = ^(){
        hostAcceptView.alpha = 0.4;
        guestAcceptView.alpha = 0.4;
        
        [UIView animateWithDuration: 0.5  delay: 0.1
                            options: UIViewAnimationCurveLinear
                         animations: ^(){
                             hostAcceptView.alpha = 1.0;
                             guestAcceptView.alpha = 1.0;
                         }
                         completion: ^(BOOL finished){
                             [UIView animateWithDuration: 0.5  delay: 0.1
                                                 options: UIViewAnimationCurveLinear
                                              animations: ^(){
                                                  hostAcceptView.alpha = 0.4;
                                                  guestAcceptView.alpha = 0.4;
                                              }
                                              completion: ^(BOOL finished){
                                                  if (currentCardValid == NO)
                                                      global_acceptViewAnimation();
                                                  else
                                                  {
                                                      hostAcceptView.alpha = 0.0;
                                                      guestAcceptView.alpha = 0.0;
                                                  }
                                              }
                              ];
                         }
        ];
    };
    
    // 完成guestHandCard移动到targetCard的动画
    global_guestHandCardToTarget = ^(NSInteger index, BOOL isToHost)
    {
        guestHandCard[index].transform = CGAffineTransformIdentity;
        
        CGPoint destination;
        UIImageView* matchedViewEffect;
        
        if (isToHost)
        {
            destination = CGPointMake(140, 160);
            matchedViewEffect = hostTargetCardEffect;
        }
        else
        {
            destination = CGPointMake(350, 160);
            matchedViewEffect = guestTargetCardEffect;
        }
        
        GameDataManager* pData = [GameDataManager sharedInstance];
        NSTimeInterval interval;
        if (pData.difficulty == 3)
            interval = 0.5;
        else if(pData.difficulty == 2)
            interval = 0.75;
        else interval = 1.0;
        
        [UIView animateWithDuration: interval  delay: 0.0
                            options: UIViewAnimationCurveLinear
                         animations: ^(){
                             guestHandCard[index].center = destination;
                         }
                         completion: ^(BOOL finished){
                             if (isToHost)
                                 blackRoundView.highlighted = YES;
                             else 
                                 whiteRoundView.highlighted = YES;
                             
                             PkManager* pk = [PkManager sharedInstance];
                             BOOL ok;
                             if (isToHost)
                                 ok = [pk checkCardWhetherMarch:hostTargetCardEffect withView:guestHandCard[index]];
                             else 
                                 ok = [pk checkCardWhetherMarch:guestTargetCardEffect withView:guestHandCard[index]];
                             
                             if (currentCardValid == NO && (pk.hostCardCount == 0 ||pk.guestCardCount == 0))
                                 ok = YES;
                                 
                             if (ok)
                             {
                                 // 赋值
                                 matchedViewEffect.image = guestHandCard[index].image;
                                 [matchedViewEffect.layer setValue:[guestHandCard[index].layer valueForKey:@"CardNumber"] 
                                                            forKey:@"CardNumber"];
                             
                                 // draw guestHandCard
                                 [self drawAndGetImage:guestHandCard[index] drawHost:NO];
                             
                                 // target scale effect
                                 if (matchedViewEffect == hostTargetCardEffect)
                                     global_drawTargetCardAnimation_Step2_Host(0.3, 0, YES);
                                 else 
                                     global_drawTargetCardAnimation_Step2_Guest(0.3, 0, YES);
                             
                                 // minus score
                                 [[GameDataManager sharedInstance] minusGuestScore];
                                 global_drawGuestHandCard(guestHandCard[index].tag-400, 0.2);
                                 
                                 // gameover,禁止对卡片操作
                                 if ([[GameDataManager sharedInstance] guestScore] == 0)
                                 {
                                     for (NSInteger i = 0; i < 4; i++)
                                     {
                                         hostHandCard[i].userInteractionEnabled  = NO;
                                         guestHandCard[i].userInteractionEnabled = NO;
                                     }
                                 }
                             
                                 [self setRoleView];
                             
                                 // 变更bgm为紧张节奏
                                 if ([[GameDataManager sharedInstance] hostScore] == 5 ||
                                     [[GameDataManager sharedInstance] guestScore] == 5)
                                 {
                                     if (endBGMHasBegan == NO)
                                     {
                                         endBGMHasBegan = YES;
                                         [[AudioManager sharedInstance] PlayBGM:@"FightingWillEndBGM"];
                                     }    
                                 }
                             }
                             else
                             {
                                 // 移动的HandCard回归原位
                                 CGFloat rotation = M_PI*guestHandCardRot[index];
                                 CGPoint position = CGPointMake(guestHandCardPosX[index], guestHandCardPosY[index]);
                                 
                                 [UIView animateWithDuration: 0.2  delay: 0.0
                                                     options: UIViewAnimationCurveLinear
                                                  animations: ^(){
                                                      guestHandCard[index].center = position;
                                                      guestHandCard[index].transform = CGAffineTransformMakeRotation(rotation);
                                                  }
                                                  completion: nil
                                  ];

                             }
                        }
         ];
    };
    }
}

@end
